package cn.neusoft.controller;

import cn.neusoft.pojo.Food;
import cn.neusoft.query.FoodQuery;
import cn.neusoft.service.IFoodService;
import cn.neusoft.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/food")
public class FoodController {

    @Autowired
    IFoodService foodService;

    @PostMapping      //  请求方式 + 请求路径   post  /food
    public ResultBean save(@RequestBody Food food){
        System.out.println("----FoodController-----save--------");
        System.out.println(food);
        if (food.getFoodId()==null){
            return foodService.add(food);
        }
        return foodService.update(food);
    }

    //  delete   /food/1003
    @DeleteMapping("/{id}")   // http://localhost:8080/food/1003
    public ResultBean del(@PathVariable("id") Integer id){
        System.out.println("-------FoodController--------del-------------");
        System.out.println(id);
        return foodService.delete(id);
    }

    //  get   /food/1004
    @GetMapping("/{id}")   // http://localhost:8080/food/1003
    public ResultBean getById(@PathVariable("id") Integer id){
        System.out.println("-------FoodController--------getById-------------");
        System.out.println(id);
        return foodService.getById(id);
    }

    @GetMapping("/all")    //  get  /food/all
    public ResultBean getAll(){
        System.out.println("-------FoodController-----getAll--------");
        return foodService.getAll();
    }

    @PostMapping("/page")   // post  /food/page
    public ResultBean getByPage(@RequestBody FoodQuery foodQuery){
        System.out.println("-------FoodController--------getByPage-------------");
        System.out.println(foodQuery);
        return foodService.getByPage(foodQuery);
    }

    @PostMapping("/batch/{ids}")   // post + /food/batch
    public ResultBean batchDel(@PathVariable("ids") String ids){
        System.out.println("----------FoodController---------batchDel---------------");
        System.out.println(ids); //接收到的参数格式 ： 21,19
        String[] strIds = ids.split(",");  //字符串拆分  [21,19]
        System.out.println(Arrays.toString(strIds));
        List<Integer> numids = new ArrayList<>();  //创建一个Integer集合  service层需要的参数类型
        for (String strid: strIds) {
            numids.add(Integer.parseInt(strid));//将数组中的每一项转型为Integer再加入到集合中
        }
        System.out.println(numids);
        return foodService.batchDel(numids);
    }


    /*
    根据商家编号查询该商家的所有餐品
     */
    @GetMapping("/business/{bid}")    //  get  /food/business/1
    public ResultBean getByBusinessId(@PathVariable("bid") Integer businessId){
        System.out.println("---------FoodController--------getByBusinessId-----------");
        System.out.println(businessId);
        return foodService.getByBusinessId(businessId);
    }

}
